<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
      <el-form-item label="时间范围">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-select v-model="queryParams.customerName" filterable clearable placeholder="请选择客户" style="width: 200px">
          <el-option v-for="item in customerOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="货物名称" prop="goodsName">
        <el-select v-model="queryParams.goodsName" filterable clearable placeholder="请选择货物" style="width: 200px">
          <el-option v-for="item in goodsOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <el-card shadow="never">
      <div slot="header">
        <span>利润分析概览</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover">
            <div slot="header">总销售额</div>
            <div class="statistic-value">¥ {{ overviewData.totalSales }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div slot="header">总成本</div>
            <div class="statistic-value">¥ {{ overviewData.totalCost }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div slot="header">总利润</div>
            <div class="statistic-value">¥ {{ overviewData.totalProfit }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div slot="header">利润率</div>
            <div class="statistic-value">{{ overviewData.profitRate }}%</div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 标签名转换：Vue 自动将驼峰命名的组件名 (ProfitChart) 转换为短横线命名 (profit-chart)，这是 HTML 的规范要求。
属性传递：:chart-data="chartData" 将父组件 (profit-analysis.vue) 的 chartData 数据通过 props 传递给子组件 (profitChart.vue)。 -->
    <el-card shadow="never" class="mt20">
      <div slot="header">
        <span>利润趋势</span>
      </div>
      <div style="height: 350px">
        <profit-chart :chart-data="chartData" />
      </div>
    </el-card>

    <el-card shadow="never" class="mt20">
      <div slot="header">
        <span>利润明细</span>
      </div>
      <el-table v-loading="loading" :data="profitList">
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="货物名称" align="center" prop="goodsName" />
        <el-table-column label="销售数量" align="center" prop="saleQuantity" />
        <el-table-column label="销售单价" align="center" prop="salePrice">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.salePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销售总价" align="center" prop="saleTotal">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.saleTotal }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采购单价" align="center" prop="purchasePrice">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.purchasePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采购总价" align="center" prop="purchaseTotal">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.purchaseTotal }}</span>
          </template>
        </el-table-column>
        <el-table-column label="额外成本" align="center" prop="extraCost">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.extraCost }}</span>
          </template>
        </el-table-column>
        <el-table-column label="利润" align="center" prop="profit">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.profit >= 0 ? '#67C23A' : '#F56C6C' }">
              ¥ {{ scope.row.profit }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="利润率" align="center" prop="profitRate">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.profitRate >= 0 ? '#67C23A' : '#F56C6C' }">
              {{ scope.row.profitRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="销售时间" align="center" prop="saleTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.saleTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import ProfitChart from "./profitChart";

// mock API
function listProfit(queryParams) {
  return new Promise(resolve => {
    setTimeout(() => {
      const data = [
        {
          id: 1,
          customerName: "华南船舶公司",
          goodsName: "焊接钢板",
          saleQuantity: 80,
          salePrice: 60.00,
          saleTotal: 4800.00,
          purchasePrice: 50.00,
          purchaseTotal: 4000.00,
          extraCost: 150.00,
          profit: 650.00,
          profitRate: 13.54,
          saleTime: "2024-12-10 10:00:00"
        },
        {
          id: 2,
          customerName: "东部工业集团",
          goodsName: "焊丝",
          saleQuantity: 40,
          salePrice: 35.00,
          saleTotal: 1400.00,
          purchasePrice: 30.00,
          purchaseTotal: 1200.00,
          extraCost: 120.00,
          profit: 80.00,
          profitRate: 5.71,
          saleTime: "2024-12-12 15:30:00"
        },
        {
          id: 3,
          customerName: "宁波船务有限公司",
          goodsName: "电动工具",
          saleQuantity: 15,
          salePrice: 220.00,
          saleTotal: 3300.00,
          purchasePrice: 200.00,
          purchaseTotal: 3000.00,
          extraCost: 100.00,
          profit: 200.00,
          profitRate: 6.06,
          saleTime: "2024-12-15 09:45:00"
        },
        {
          id: 4,
          customerName: "华南船舶公司",
          goodsName: "焊丝",
          saleQuantity: 30,
          salePrice: 40.00,
          saleTotal: 1200.00,
          purchasePrice: 30.00,
          purchaseTotal: 900.00,
          extraCost: 50.00,
          profit: 250.00,
          profitRate: 20.83,
          saleTime: "2024-12-18 14:20:00"
        },
        {
          id: 5,
          customerName: "东部工业集团",
          goodsName: "焊接钢板",
          saleQuantity: 50,
          salePrice: 65.00,
          saleTotal: 3250.00,
          purchasePrice: 50.00,
          purchaseTotal: 2500.00,
          extraCost: 200.00,
          profit: 550.00,
          profitRate: 16.92,
          saleTime: "2024-12-20 11:10:00"
        }
      ];

      // 过滤数据
      let filteredData = [...data];
      if (queryParams.customerName) {
        filteredData = filteredData.filter(item => item.customerName === queryParams.customerName);
      }
      if (queryParams.goodsName) {
        filteredData = filteredData.filter(item => item.goodsName === queryParams.goodsName);
      }
      if (queryParams.startTime && queryParams.endTime) {
        filteredData = filteredData.filter(item => {
          const saleDate = new Date(item.saleTime).getTime();
          return saleDate >= new Date(queryParams.startTime).getTime() &&
            saleDate <= new Date(queryParams.endTime + ' 23:59:59').getTime();
        });
      }

      // 分页处理
      const total = filteredData.length;
      const pageSize = queryParams.pageSize || 10;
      const pageNum = queryParams.pageNum || 1;
      const rows = filteredData.slice((pageNum - 1) * pageSize, pageNum * pageSize);

      resolve({
        rows,
        total,
        overview: {
          totalSales: filteredData.reduce((sum, item) => sum + item.saleTotal, 0).toFixed(2),
          totalCost: filteredData.reduce((sum, item) => sum + item.purchaseTotal + item.extraCost, 0).toFixed(2),
          totalProfit: filteredData.reduce((sum, item) => sum + item.profit, 0).toFixed(2),
          profitRate: (filteredData.reduce((sum, item) => sum + item.profit, 0) /
            filteredData.reduce((sum, item) => sum + item.saleTotal, 0) * 100 || 0).toFixed(2)
        },
        chartData: {
          dates: [...new Set(filteredData.map(item => item.saleTime.split(' ')[0]))].sort(),
          profits: [...new Set(filteredData.map(item => item.saleTime.split(' ')[0]))].sort()
            .map(date => filteredData.filter(item => item.saleTime.startsWith(date))
              .reduce((sum, item) => sum + item.profit, 0))
        }
      });
    }, 500);
  });
}

function getCustomerOptions() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(["华南船舶公司", "东部工业集团", "宁波船务有限公司"]);
    }, 200);
  });
}

function getGoodsOptions() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(["焊接钢板", "焊丝", "电动工具"]);
    }, 200);
  });
}

export default {
  name: "ProfitAnalysis",
  components: { ProfitChart },
  data() {
    return {
      loading: false,
      dateRange: [],
      customerOptions: [],
      goodsOptions: [],
      overviewData: {
        totalSales: 0,
        totalCost: 0,
        totalProfit: 0,
        profitRate: 0
      },
      chartData: {
        dates: [],
        profits: []
      },
      profitList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: undefined,
        goodsName: undefined,
        startTime: undefined,
        endTime: undefined
      }
    };
  },
  created() {
    this.getCustomerOptions();
    this.getGoodsOptions();
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.startTime = undefined;
        this.queryParams.endTime = undefined;
      }

      listProfit(this.queryParams).then(response => {
        this.profitList = response.rows;
        this.total = response.total;
        this.overviewData = response.overview;
        this.chartData = response.chartData;
        this.loading = false;
      });
    },
    getCustomerOptions() {
      getCustomerOptions().then(response => {
        this.customerOptions = response;
      });
    },
    getGoodsOptions() {
      getGoodsOptions().then(response => {
        this.goodsOptions = response;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        customerName: undefined,
        goodsName: undefined,
        startTime: undefined,
        endTime: undefined
      };
      this.handleQuery();
    },
    handleExport() {
      this.$modal.confirm('确认导出利润分析数据?').then(() => {
        this.download('/profit/export', {
          ...this.queryParams
        }, `利润分析_${new Date().getTime()}.xlsx`);
      });
    }
  }
};
</script>

<style scoped>
.statistic-value {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 10px 0;
  color: #409EFF;
}

.mt20 {
  margin-top: 20px;
}
</style>